﻿@using GlobalResources;
@using Microsoft.Azure.IoTSuite.Connectedfactory.WebApp.Models
@using Microsoft.Azure.IoTSuite.Connectedfactory.WebApp.Security

@model OpcSessionModel


<table class="table_container_twin">
    <thead>
        <tr>
            <th class="table_header">@Strings.SupervisorHeaderId</th>
            <th class="table_header">@Strings.SupervisorHeaderConnStatus</th>
            <th class="table_header">@Strings.SupervisorScanStatus</th>
            <th class="table_header">@Strings.TableHeaderScan</th>
            <th class="table_header">@Strings.TableHeaderPort</th>
        </tr>
    </thead>
    <tbody>
        @{ int i = 0;}
        @{ string toggleLabel = null;}
        @{ string connectStatus = Strings.supervisorDisconnected;}
        @if (Model.supervisorList != null)
        {
            foreach (var supervisor in Model.supervisorList)
            {
                <tr class="table_ListItem_container">
                    <td id="supervisor_table_content_id@(i)" class="table_content">
                        @supervisor.supervisorModel.Id
                    </td>
                    @if (@supervisor.supervisorModel.Connected == true)
                    {
                        connectStatus = Strings.supervisorConnected;
                    }
                    <td id="supervisor_table_content_connStatus@(i)" class="table_content">
                        @connectStatus
                    </td>
                    <td id="supervisor_table_content@(i)" class="table_content">
                        <label class="label">
                            <div class="toggle">
                                @if (@supervisor.supervisorModel.Discovery.ToString() == "Fast")
                                {
                                    <input id="toggle@(i)" class="toggle-state" type="checkbox" name="check" checked="checked" value="@supervisor.supervisorModel.Id" onchange="checkToggle(this, @i)" />

                                    toggleLabel = Strings.ScanToggleOn;
                                }
                                else
                                {
                                    <input id="toggle@(i)" class="toggle-state" type="checkbox" name="check" value="@supervisor.supervisorModel.Id" onchange="checkToggle(this, @i)" />

                                    toggleLabel = Strings.ScanToggleOff;
                                }
                                <div class="toggle-inner">
                                    <div class="indicator"></div>
                                </div>
                                <div class="active-bg"></div>
                            </div>
                            <div id="label-text@(i)" class="label-text">@toggleLabel</div>
                        </label>
                    </td>
                    <td>
                        @if ((@supervisor.supervisorModel.DiscoveryConfig != null) && (@supervisor.supervisorModel.DiscoveryConfig.AddressRangesToScan != "") && (@supervisor.supervisorModel.DiscoveryConfig.AddressRangesToScan != null))
                        {
                            <a href="#" id="address@(i)" class="table_content_link" onclick="openPanel(@i)">@supervisor.supervisorModel.DiscoveryConfig.AddressRangesToScan</a>

                        }
                        else
                        {
                            <a href="#" id="address@(i)" class="table_content_link" onclick="openPanel(@i)">@Strings.Default</a>
                        }
                    </td>
                    <td>
                        @if ((@supervisor.supervisorModel.DiscoveryConfig != null) && (@supervisor.supervisorModel.DiscoveryConfig.PortRangesToScan != "") && (@supervisor.supervisorModel.DiscoveryConfig.PortRangesToScan != null))
                        {
                            <a href="#" id="port@(i)" class="table_content_link" onclick="openPanel(@i)">@supervisor.supervisorModel.DiscoveryConfig.PortRangesToScan</a>

                        }
                        else
                        {
                            <a href="#" id="port@(i)" class="table_content_link" onclick="openPanel(@i)">@Strings.Default</a>
                        }
                    </td>
                    @if (supervisor.HasApplication == true)
                    {
                        <td id="supervisor_button@(i)" class="table_content">
                            <label class="label">
                                @Html.ActionLink(@Strings.ButtonEndpoints, "Start", "Browser", new { supervisorId = @supervisor.supervisorModel.Id }, new { @class = "dashboard_link" })
                            </label>
                        </td>
                    }
                </tr>
                i++;
            }
        }
    </tbody>
</table>

<script type="text/javascript">
    var currentSupervisor;
    var supervisors = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.supervisorList));

    function checkToggle(element, index) {
        if (element.checked == true) {
            $("#label-text" + index).html('@Strings.ScanToggleOn');
            currentSupervisor = index;
            setScanSupervisor(element.value, element.checked, supervisors[index]);
        } else {
            $("#label-text" + index).html('@Strings.ScanToggleOff');
            setScanSupervisor(element.value, element.checked, supervisors[index]);
        }
    }

    function openPanel(index) {
        currentSupervisor = index;
        $("#scanContextPanel").removeClass("overlay-close").addClass("overlay-right-open");
    }

    function apply() {
        $("#errorIpRange").hide();
        $("#errorPortRange").hide();
        setScanSupervisor(supervisors[currentSupervisor].supervisorModel.id, true, supervisors[currentSupervisor]);
    }

    function isValidIpRange(input) {
        var isValid = false;
        var ipAddress = input.substring(0, input.indexOf("/"));

        if (input === "") {
            isValid = true;
        }
        else {
            isValid = /^(?=\d+\.\d+\.\d+\.\d+$)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.?){4}$/.test(ipAddress);
        }
        return isValid;
    }

    function isValidPortRange(input) {
        var isValid = false;
        var portAddress1 = input.substring(0, input.indexOf("-"));
        var portAddress2 = input.substring(input.indexOf("-") + 1);

        if (input === "") {
            isValid = true;
        } else {
            isValid = (parseInt(portAddress1) >= 0 && parseInt(portAddress1) <= 65535) &&
                      (parseInt(portAddress2) >= 0 && parseInt(portAddress2) <= 65535);
        }
        return isValid;
    }

    function setScanSupervisor(supervisorId, scanStatus, supervisor) {
        var ipMask = "";
        var portRange = "";

        if ($("#scanContextPanel").hasClass("overlay-right-open")) {
            portRange = $("#portRange").val();
            ipMask = $("#ipAddressMask").val();
        } else {
            if (supervisor.supervisorModel.hasOwnProperty('discoveryConfig')) {
                if (supervisor.supervisorModel.discoveryConfig.hasOwnProperty('addressRangesToScan')) {
                    ipMask = supervisor.supervisorModel.discoveryConfig.addressRangesToScan;
                } else {
                    ipMask = "";
                }

                if (supervisor.supervisorModel.discoveryConfig.hasOwnProperty('portRangesToScan')) {
                    portRange = supervisor.supervisorModel.discoveryConfig.portRangesToScan;
                } else {
                    portRange = "";
                }
            }
        }

        if (isValidIpRange(ipMask) === false) {
            $("#errorIpRange").show();
            return;
        }
        if (isValidPortRange(portRange) === false) {
            $("#errorPortRange").show();
            return;
        }

        $.post({
            url: "/Supervisor/SetScanStatus",
            data: { __RequestVerificationToken: $('[name=__RequestVerificationToken]').val(), supervisorId: supervisorId, scanStatus: scanStatus, ipMask: ipMask, portRange: portRange },
            success: function onSuccess(response) {
                $('#scanContextPanel').removeClass("overlay-right-open").addClass('overlay-close')
                setTimeout(getSupervisors, 1000);
            },
            error: function (response) {
                console.error("error setting scan status: ", response.d, response.responseText);
                onFailure(response);
            },
        });
    }

    function getSupervisors() {
        $.post({
            url: "/Supervisor/UpdateModel",
            data: { __RequestVerificationToken: $('[name=__RequestVerificationToken]').val() },
            cache: false,
            success: function onSuccess(response) {
                supervisors = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.supervisorList));
                $("#partial").html(response);
            },
            error: function (response) {
                console.error("error getting supervisors: ", response.d, response.responseText);
                onFailure(response);
            },
        });
    }

    function onFailure(response) {
        $("#contextpanel").html("@Strings.Error");
        $("#errorContextPanel").show();
        $("#errorHeader").html(sessionModel.ErrorHeader);
        $("#errorMessage").html(sessionModel.ErrorMessage);
        $("#proceedButton").hide();
        $("#cancelButton").hide();
        $(".dashboard-cancel-icon").show();
        $(".dashboard_contextpanel_select_filter_button").css({ "margin-left": marginLeft });
    }

    function closeContextPanel(id) {
        $("#contextpanel").addClass("overlay-close").removeClass("overlay-right-open");
    }
</script>
